#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
中文字体安装脚本

自动检测系统并安装适合的中文字体，解决matplotlib中文显示乱码问题。

作者: 代码工程师
版本: 1.0.0
日期: 2025-01-29
"""

import os
import sys
import subprocess
import platform
import urllib.request
from pathlib import Path

def run_command(cmd, description=""):
    """运行系统命令"""
    print(f"🔄 {description}")
    print(f"执行命令: {' '.join(cmd)}")
    
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, check=True)
        print("✅ 命令执行成功")
        if result.stdout:
            print(result.stdout)
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ 命令执行失败: {e}")
        if e.stderr:
            print(f"错误信息: {e.stderr}")
        return False
    except FileNotFoundError:
        print(f"❌ 命令未找到: {cmd[0]}")
        return False

def detect_system():
    """检测操作系统类型"""
    system = platform.system().lower()
    
    if system == 'linux':
        # 检测Linux发行版
        if os.path.exists('/etc/debian_version'):
            return 'debian'
        elif os.path.exists('/etc/ubuntu_version'):
            return 'ubuntu'
        elif os.path.exists('/etc/redhat-release'):
            return 'redhat'
        elif os.path.exists('/etc/centos-release'):
            return 'centos'
        elif os.path.exists('/etc/fedora-release'):
            return 'fedora'
        elif os.path.exists('/etc/arch-release'):
            return 'arch'
        else:
            return 'linux'
    elif system == 'darwin':
        return 'macos'
    elif system == 'windows':
        return 'windows'
    else:
        return 'unknown'

def install_fonts_debian_ubuntu():
    """在Debian/Ubuntu系统上安装中文字体"""
    print("\n📦 在Debian/Ubuntu系统上安装中文字体...")
    
    # 更新包列表
    if not run_command(['sudo', 'apt-get', 'update'], "更新包列表"):
        return False
    
    # 安装中文字体包
    font_packages = [
        'fonts-noto-cjk',  # Google Noto CJK字体
        'fonts-wqy-microhei',  # 文泉驿微米黑
        'fonts-wqy-zenhei',  # 文泉驿正黑
        'fonts-arphic-ukai',  # AR PL UKai字体
        'fonts-arphic-uming'  # AR PL UMing字体
    ]
    
    success_count = 0
    for package in font_packages:
        if run_command(['sudo', 'apt-get', 'install', '-y', package], 
                      f"安装字体包: {package}"):
            success_count += 1
    
    print(f"\n✅ 成功安装 {success_count}/{len(font_packages)} 个字体包")
    return success_count > 0

def install_fonts_redhat_centos():
    """在RedHat/CentOS系统上安装中文字体"""
    print("\n📦 在RedHat/CentOS系统上安装中文字体...")
    
    # 检测包管理器
    package_manager = 'yum'
    if os.path.exists('/usr/bin/dnf'):
        package_manager = 'dnf'
    
    font_packages = [
        'google-noto-sans-cjk-fonts',  # Google Noto CJK字体
        'wqy-microhei-fonts',  # 文泉驿微米黑
        'wqy-zenhei-fonts',  # 文泉驿正黑
    ]
    
    success_count = 0
    for package in font_packages:
        if run_command(['sudo', package_manager, 'install', '-y', package], 
                      f"安装字体包: {package}"):
            success_count += 1
    
    print(f"\n✅ 成功安装 {success_count}/{len(font_packages)} 个字体包")
    return success_count > 0

def install_fonts_arch():
    """在Arch Linux系统上安装中文字体"""
    print("\n📦 在Arch Linux系统上安装中文字体...")
    
    font_packages = [
        'noto-fonts-cjk',  # Google Noto CJK字体
        'wqy-microhei',  # 文泉驿微米黑
        'wqy-zenhei',  # 文泉驿正黑
    ]
    
    success_count = 0
    for package in font_packages:
        if run_command(['sudo', 'pacman', '-S', '--noconfirm', package], 
                      f"安装字体包: {package}"):
            success_count += 1
    
    print(f"\n✅ 成功安装 {success_count}/{len(font_packages)} 个字体包")
    return success_count > 0

def install_fonts_macos():
    """在macOS系统上安装中文字体"""
    print("\n📦 在macOS系统上安装中文字体...")
    print("macOS通常已经包含中文字体，如PingFang SC")
    
    # 检查是否安装了Homebrew
    if os.path.exists('/usr/local/bin/brew') or os.path.exists('/opt/homebrew/bin/brew'):
        print("检测到Homebrew，尝试安装额外的中文字体...")
        
        font_casks = [
            'font-noto-sans-cjk',
            'font-source-han-sans'
        ]
        
        success_count = 0
        for cask in font_casks:
            if run_command(['brew', 'install', '--cask', cask], 
                          f"安装字体: {cask}"):
                success_count += 1
        
        print(f"\n✅ 成功安装 {success_count}/{len(font_casks)} 个字体")
        return success_count > 0
    else:
        print("建议安装Homebrew以便安装额外的中文字体")
        print("访问: https://brew.sh/")
        return True

def install_fonts_windows():
    """在Windows系统上安装中文字体"""
    print("\n📦 Windows系统字体安装...")
    print("Windows通常已经包含中文字体，如微软雅黑")
    print("如果仍有问题，请手动下载并安装以下字体:")
    print("- Google Noto Sans CJK SC")
    print("- Source Han Sans SC (思源黑体)")
    return True

def download_font_file(url, filename):
    """下载字体文件"""
    try:
        print(f"📥 下载字体文件: {filename}")
        urllib.request.urlretrieve(url, filename)
        print(f"✅ 下载完成: {filename}")
        return True
    except Exception as e:
        print(f"❌ 下载失败: {e}")
        return False

def refresh_font_cache():
    """刷新字体缓存"""
    print("\n🔄 刷新字体缓存...")
    
    system = detect_system()
    
    if system in ['debian', 'ubuntu', 'redhat', 'centos', 'fedora', 'arch', 'linux']:
        # Linux系统
        commands = [
            ['fc-cache', '-fv'],
            ['fc-list', ':', 'family', '|', 'grep', '-i', 'noto']
        ]
        
        for cmd in commands:
            run_command(cmd, f"执行: {' '.join(cmd)}")
    
    elif system == 'macos':
        print("macOS会自动刷新字体缓存")
    
    elif system == 'windows':
        print("Windows会自动刷新字体缓存")

def verify_chinese_fonts():
    """验证中文字体安装"""
    print("\n🔍 验证中文字体安装...")
    
    try:
        import matplotlib.font_manager as fm
        import matplotlib.pyplot as plt
        
        # 获取所有可用字体
        available_fonts = [f.name for f in fm.fontManager.ttflist]
        
        # 检查中文字体
        chinese_fonts = [
            'Noto Sans CJK SC',
            'Source Han Sans SC',
            'WenQuanYi Micro Hei',
            'SimHei',
            'Microsoft YaHei',
            'PingFang SC',
            'Hiragino Sans GB'
        ]
        
        found_fonts = []
        for font in chinese_fonts:
            if font in available_fonts:
                found_fonts.append(font)
                print(f"✅ 找到中文字体: {font}")
        
        if found_fonts:
            print(f"\n🎉 成功！找到 {len(found_fonts)} 个中文字体")
            
            # 测试中文显示
            plt.rcParams['font.sans-serif'] = found_fonts[:1] + plt.rcParams['font.sans-serif']
            plt.rcParams['axes.unicode_minus'] = False
            
            fig, ax = plt.subplots(figsize=(6, 4))
            ax.text(0.5, 0.5, '中文字体测试\nChinese Font Test', 
                   fontsize=16, ha='center', va='center')
            ax.set_xlim(0, 1)
            ax.set_ylim(0, 1)
            ax.set_title('字体测试 Font Test')
            ax.axis('off')
            
            test_file = 'chinese_font_test.png'
            plt.savefig(test_file, dpi=100, bbox_inches='tight')
            plt.close()
            
            if os.path.exists(test_file):
                print(f"✅ 中文字体测试成功，测试图片已保存: {test_file}")
                os.remove(test_file)  # 清理测试文件
            
            return True
        else:
            print("❌ 未找到中文字体")
            return False
            
    except ImportError:
        print("❌ matplotlib未安装，无法验证字体")
        return False
    except Exception as e:
        print(f"❌ 字体验证失败: {e}")
        return False

def main():
    """主函数"""
    print("🧬 BioParam_Sampler 中文字体安装工具")
    print("=" * 50)
    
    # 检测系统
    system = detect_system()
    print(f"🖥️  检测到系统类型: {system}")
    
    # 根据系统类型安装字体
    success = False
    
    if system in ['debian', 'ubuntu']:
        success = install_fonts_debian_ubuntu()
    elif system in ['redhat', 'centos', 'fedora']:
        success = install_fonts_redhat_centos()
    elif system == 'arch':
        success = install_fonts_arch()
    elif system == 'macos':
        success = install_fonts_macos()
    elif system == 'windows':
        success = install_fonts_windows()
    else:
        print(f"❌ 不支持的系统类型: {system}")
        print("请手动安装中文字体")
        return
    
    if success:
        # 刷新字体缓存
        refresh_font_cache()
        
        # 验证字体安装
        if verify_chinese_fonts():
            print("\n🎉 中文字体安装和配置完成！")
            print("\n💡 使用提示:")
            print("   现在可以正常使用BioParam_Sampler的可视化功能")
            print("   运行: python bioparam_sampler.py -c config.json --visualize")
        else:
            print("\n⚠️  字体安装完成，但验证失败")
            print("   请重启Python环境后再试")
    else:
        print("\n❌ 字体安装失败")
        print("\n🔧 手动解决方案:")
        print("   1. 检查网络连接")
        print("   2. 确认有sudo权限")
        print("   3. 手动下载并安装中文字体")
        print("   4. 参考README.md中的字体配置说明")

if __name__ == '__main__':
    main()